using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Web.Configuration;
using SubSonic;

using Impact.Infrastructure;
using Impact.Controllers;
using Impact.Model.Objects;
using Impact.Views;
using Impact.Web.Foundation;
using Impact.Web.Foundation.Controls;


namespace Impact.Web.Admin
{
    /// <summary>
    /// code-behind for the edit page view
    /// </summary>
    public partial class EditPage : PageBase, IPageEditorView
    {
        private EditPageController controller;
        private const string ConvertToPage = "Convert to Page";
        private const string ConvertToLink = "Convert to Link";

        /// <summary>
        /// override of onload to perform startup functionality
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            controller = new EditPageController( this, UserId );

            // first fill the drop downs
            PopulateTemplateDropDown();
            PopulateParentDropDown();

            // controller.initialize populates the form, so the dropdown must
            // be populated first
            controller.Initialize( !IsPostBack );

        }

        /// <summary>
        /// event handler for the edit plugins button
        /// </summary>
        protected void EditPluginsCommand( object sender, CommandEventArgs e )
        {
            Redirect( string.Format( "EditPlugins.aspx?pid={0}&ReturnUrl={1}", Request.QueryString["pid"], Server.UrlEncode( Request.Url.ToString() ) ) );
        }

        /// <summary>
        /// fill the template drop down with all available templates
        /// </summary>
        private void PopulateTemplateDropDown()
        {
            template.DataSource = controller.GetTemplates();
            template.DataTextField = Template.Columns.Name;
            template.DataValueField = Template.Columns.TemplateID;
            template.DataBind();
        }


        /// <summary>
        /// fill the parent drop down with all top-level pages that isn't the one currently loaded
        /// </summary>
        private void PopulateParentDropDown()
        {
            parentPage.DataSource = controller.GetAvailableParents();
            parentPage.DataTextField = ImpactPage.Columns.PageKey;
            parentPage.DataValueField = ImpactPage.Columns.PageId;
            parentPage.DataBind();
        }

        /// <summary>
        /// event handler for the submit button
        /// </summary>
        protected void SubmitCommand( object sender, EventArgs e )
        {
            if (Page.IsValid)
            {
                controller.SavePage();
                MessageBox.Show("Your changes have been saved.");
                Redirect(AdminHome);
            }
        }

        /// <summary>
        /// event handler for the cancel button
        /// </summary>
        protected void CancelCommand( object sender, EventArgs e )
        {
            Redirect( AdminHome );
        }

        /// <summary>
        /// event handler for the button to toggle this page from a standard page to a hyperlink
        /// </summary>
        protected void ConvertBtn_Command( object sender, CommandEventArgs e )
        {
            if ( normalSection.Visible ) // convert to direct link
            {
                convertButton.Text = ConvertToPage;
                normalSection.Visible = false;
                linkSection.Visible = true;
                linkTargetRequired.Enabled = true;
            }
            else
            {
                convertButton.Text = ConvertToLink;
                normalSection.Visible = true;
                linkSection.Visible = false;
                linkTargetRequired.Enabled = false;
            }

        }

        #region IEditPageView Members

        /// <summary>
        /// uses the given object and fills all appropriate form fields with its data
        /// </summary>
        public void PopulateForm( ImpactPage page )
        {
            ViewState[ImpactPage.Columns.PageId] = page.PageId;

            pageKey.Text = page.PageKey;
            caption.Text = page.Caption;
            parentPage.SelectedValue = page.ParentPageId.ToString();
            template.SelectedValue = page.TemplateId.ToString();
            pageTitle.Text = page.Title;
            pageBody.Value = page.Body;

            if ( page.PageType.Equals( PageType.Hyperlink ) )
            {
                convertButton.Text = ConvertToPage;
                normalSection.Visible = false;
                linkSection.Visible = true;

                linkTarget.Text = page.LinkTarget;
            }

        }

        /// <summary>
        /// gets data out of the appropriate form fields and puts it into a page object
        /// </summary>
        public ImpactPage RetrieveFormData()
        {
            ImpactPage page = null;
            if ( ViewState[ImpactPage.Columns.PageId] != null )
            {
                int pageId = (int)ViewState[ImpactPage.Columns.PageId];
                if ( pageId > 0 )
                {
                    page = controller.GetPage( pageId );
                }
            }

            if ( page == null )
            {
                page = new ImpactPage();
            }

            page.PageKey = Utility.StripNonAlphaNumeric( pageKey.Text.Trim() );
            page.Caption = caption.Text;
            page.Title = pageTitle.Text;
            page.Body = pageBody.Value;

            if ( linkSection.Visible )
            {
                page.LinkTarget = linkTarget.Text;
            }
            else
            {
                page.LinkTarget = string.Empty;
            }

            if ( parentPage.SelectedValue.Length > 0 )
            {
                page.ParentPageId = Int32.Parse( parentPage.SelectedValue );
            }
            else
            {
                page.ParentPageId = -1;
            }
            if ( template.SelectedValue.Length > 0 )
            {
                page.TemplateId = Int32.Parse( template.SelectedValue );
            }
            else
            {
                page.TemplateId = -1;
            }

            MembershipUser currentUser = Membership.GetUser();
            page.ModifiedOn = DateTime.Now;
            page.ModifiedBy = currentUser.ProviderUserKey.ToString();

            return page;
        }

        #endregion



    }
}
